import os
import subprocess

from app.utils import System
from app.utils import File


def create_systemd_service(service_name):
    if System.get_system_name() == "Linux":
        print("设置开机自启动")
        import pwd
        username = pwd.getpwuid(os.getuid()).pw_name  # 获取当前用户名
        script_path = "/home/quick-panel/"
        service_content = f"""\
        [Unit]
        Description=My Python Script
        After=network.target

        [Service]
        User={username}
        WorkingDirectory={os.getcwd()}
        ExecStart=nohup {os.getcwd()}/main &
        Restart=always

        [Install]
        WantedBy=multi-user.target
        """
        service_file = f"/etc/systemd/system/{service_name}.service"
        with open(service_file, 'w') as f:
            f.write(service_content)

        os.system(f"sudo systemctl daemon-reload")
        os.system(f"sudo systemctl enable {service_name}.service")
        File.Write("./run.sh", f"nohup {os.getcwd()}/main &")

        with open(os.path.expanduser('~/.bashrc'), 'a') as file:
            file.write(f'alias qpanel="{os.getcwd() + "/main"}"\n')
        subprocess.run(["source", "~/.bashrc"], shell=True)

        return True
    elif System.get_system_name() == "Windows":

        # Windows 系统下的服务创建逻辑
        import winreg
        key = r"Software\Microsoft\Windows\CurrentVersion\Run"
        try:
            # 打开指定路径下的注册表项
            key_handle = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key, 0, winreg.KEY_WRITE)
            # 设置注册表项的值

            winreg.SetValueEx(key_handle, "QPanel面板", 0, winreg.REG_SZ, os.getcwd() + "\\run.vbs")
            # 关闭注册表项
            winreg.CloseKey(key_handle)
            File.Write("./run.bat", f'cd "{os.getcwd()}"\n"{os.getcwd()}\main.exe"')
            File.Write("./run.vbs", f"""
Set ws = CreateObject("WScript.Shell")

' 切换到指定目录
ws.CurrentDirectory = "{os.getcwd()}"

' 运行 run.bat
ws.Run "run.bat", 0, True'""")

            os.system(f'doskey qpanel={os.getcwd()}"\\main.exe" $*')

            return True
        except Exception as e:
            print(f"Error creating startup entry: {e}")
            return False
